package com.hp.jus;

import java.net.URL;
import java.util.UUID;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

/**
 * this class generates and encrypts the KEY
 * @author salemmo
 *
 */
public class JusUtils {
	
	private static String getRandomKey(String url){
		Long uuid = UUID.randomUUID().getMostSignificantBits();
		long finald = Math.abs((uuid+url.length()+System.currentTimeMillis())/1000)+url.hashCode();
		return (finald+"");
	}
	
	public static String generateKey(URL url, Integer keyLength, int keyCaps){
		String urlStr = url.toString().trim();
		
		String key = encryptURLSafe(urlStr, getRandomKey(url.toString())).replace("_", "").replace("-", "");
		
		if(keyCaps==1)
			key = key.toUpperCase();
		else if(keyCaps==-1)
			key = key.toLowerCase();
		
		if(keyLength<8)
			keyLength = 8;
		else if(keyLength > 32 && key.length()>=32)
			keyLength = 32;
			
		return key.substring(0, keyLength);
	}
	
	public static String encodeBase64(byte [] toEncode){
		Base64 base64 = new Base64(true);
		return base64.encodeToString(toEncode).trim();
	}
	
	public static String encryptURLSafe(String to_encrypt, String key){
		to_encrypt = to_encrypt.trim();
		key = key.trim();
	
		byte[] enc = null;
		try {
			enc = JusUtils.encryptBlowfish(to_encrypt, key);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return encodeBase64(enc);
	}

	private static byte[] encryptBlowfish(String to_encrypt, String strkey)throws Exception {
		SecretKeySpec key = new SecretKeySpec(strkey.getBytes(), "Blowfish");
		Cipher cipher = Cipher.getInstance("Blowfish");
		cipher.init(Cipher.ENCRYPT_MODE, key);
		return cipher.doFinal(to_encrypt.getBytes());
	}
	
}
